#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen
@file: json_tools.back.py
@time: 2023/8/28 9:27
@desc:
"""
# coding:utf-8
import base64
import datetime
import json
import os
import time
import tkinter
from tkinter import ANCHOR, RAISED, END
from tkinter.ttk import *
from urllib.request import urlopen

import requests

from json_tool.baidu_api import get_access_token, api_key, secret_key
from json_tool.icon import Icon
from json_tool.utils import day_laster, get_hot_news, get_today

request_thread = None
import threading


def handle_timestamp_formate(event):
    if time_stamp_input.get():
        need_time = time_stamp_input.get().strip()
        time_local = time.localtime(int(need_time))  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "           " + str(time_format), "center")
    else:
        now_time = int(time.time())
        time_local = time.localtime(now_time)  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "           " + str(time_format), "center")


def handle_formate_timestamp(event):
    if time_formate_input.get():
        formate_data = time_formate_input.get().strip()
        if len(formate_data) == 10:
            # 转换成时间数组
            time_array = time.strptime(formate_data, "%Y-%m-%d")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                    " + str(time_format), "center")
        elif len(formate_data) == 19:  # "2023-03-21 15:11:25"
            time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M:%S")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                    " + str(time_format), "center")
        elif len(formate_data) == 16:  # "2023-04-01 14:00"
            time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                    " + str(time_format), "center")
    else:
        now_time = int(time.time())
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "                    " + str(now_time), "center")  # ADDED


def handle_get_last_time(event):
    if can_time_stamp_input.get():
        need_time = can_time_stamp_input.get().strip()
        time_local = time.localtime(int(need_time))  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "           " + str(time_format), "center")
    else:
        now_time = int(time.time())
        time_local = time.localtime(now_time)  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "           " + str(time_format), "center")


def handle_to_json(event):
    if sting_input.get():
        need_time = sting_input.get().strip()
        sting_output_button.delete('1.0', END)
        try:
            to_json = json.loads(need_time)
            last_send = json.dumps(to_json, ensure_ascii=False, indent=4, separators=(',', ':'))
            sting_output_button.insert(END, last_send, "center")  # ADDED
        except Exception as e:
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "字符串格式有误，请确认字符串使用的是为双引号\n", "center")  # ADDED
    else:
        sting_output_button.delete('1.0', END)
        sting_output_button.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED


def handle_chat_message():
    chat_message = sting_input.get().strip()
    key = api_key.strip()
    sec_key = secret_key.strip()
    if key and sec_key:
        if chat_message:
            if key and sec_key:
                url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + get_access_token(
                    api_key, secret_key)
                payload = json.dumps({
                    "messages": [
                        {
                            "role": "user",
                            "content": f"{chat_message}"
                        }
                    ]
                })
                headers = {
                    'Content-Type': 'application/json'
                }
                print(payload, f"start_handle {chat_message}")
                response = requests.request("POST", url, headers=headers, data=payload)
                print(response.text)
                response_message = response.json().get("result")
                sting_output_button.delete('1.0', END)
                sting_output_button.insert(END, response_message, "center")  # ADDED
                request_thread = None
        else:
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "请在左边输入想要查询的问题\n", "center")  # ADDED
    else:
        sting_output_button.delete('1.0', END)
        sting_output_button.insert(END, "请先配置api_key,secret_key\n", "center")  # ADDED


def start_request_baidu():
    global request_thread
    if request_thread is None or not request_thread.is_alive():
        download_thread = threading.Thread(target=handle_chat_message)
        download_thread.start()


def clean_input(event):
    sting_input.delete(0, END)


def listbox_copy(event):
    window.clipboard_clear()
    selected = last_print_text.get(ANCHOR)
    selected = selected.strip()
    window.clipboard_append(selected)


def copy_to_clipboard():
    """Copy current contents of text_entry to clipboard."""
    window.clipboard_clear()  # Optional.
    window.clipboard_append(last_print_text.get('1.0', END).rstrip().strip())


def copy_to_json_clipboard():
    """Copy current contents of text_entry to clipboard."""
    window.clipboard_clear()  # Optional.
    window.clipboard_append(sting_output_button.get('1.0', END).rstrip().strip())


def get_now_time():
    time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')  # 获取当前的时间并转化为字符串
    now_time_label.configure(text=time_str)  # 重新设置标签文本
    window.after(10, get_now_time)  # 每隔1s调用函数 get_now_time 自身获取时间


def get_current_weather():
    code = "310000"
    key = "c7d042524a1431fb932ff9d29e34eab6"
    # 1.获取API
    url = f"https://restapi.amap.com/v3/weather/weatherInfo?city={code}&key={key}&output=JSON&extensions=base"
    print(url)
    res = urlopen(url)
    data = json.loads(res.read())
    province = data['lives'][0]['province']  # 省份
    city = data['lives'][0]['city']  # 城市
    weather = data['lives'][0]['weather']  # 天气情况
    temperature = data['lives'][0]['temperature']  # 温度
    winddirection = data['lives'][0]['winddirection']  # 风向
    windpower = data['lives'][0]['windpower']  # 风力 级
    humidity = data['lives'][0]['humidity']  # 空气湿度
    reporttime = data['lives'][0]['reporttime']  # 发布时间
    msg = f"时间:{reporttime}  城市：{province}-{city}  \r\n天气:{weather}  温度:{temperature}°C  风向:{winddirection}  风力:{windpower}级  空气湿度:{humidity}%"
    print(msg)
    weather_stamp_show.configure(text=msg)  # 重新设置标签文本
    window.after(1000 * 60 * 60 * 6, get_current_weather)  # 每隔1s调用函数 gettime 自身获取时间


def handle_week_nums():
    time_str = datetime.datetime.now().weekday()  # 获取当前的时间并转化为字符串
    date_dict = {
        0: "星期一",
        1: "星期二",
        2: "星期三",
        3: "星期四",
        4: "星期五",
        5: "星期六",
        6: "星期日",
    }
    timestr = date_dict.get(time_str)
    dat_num_label.configure(text=timestr)  # 重新设置标签文本
    window.after(1000 * 60 * 60, handle_week_nums)  # 每隔1s调用函数 gettime 自身获取时间


def local_day_laster():
    send = day_laster()
    last_print_text_answer.delete('1.0', END)
    last_print_text_answer.insert(END, send, "center")  # ADDED


def local_get_today():
    send = get_today()
    last_print_text_answer.delete('1.0', END)
    last_print_text_answer.insert(END, send, "center")  # ADDED


def local_get_hot_news():
    send = get_hot_news()
    last_print_text_answer.delete('1.0', END)
    last_print_text_answer.insert(END, send, "center")  # ADDED


def can_time_stamp_show():
    show_string = "<-输入日期 xxxx-xx-xx xx:xx"
    if can_time_stamp_input.get():
        try:
            need_time = can_time_stamp_input.get().strip()
            if len(need_time) > 16:
                need_time = need_time[:16]
            # 将其转换为datetime对象，需要指定时间格式
            dt_obj = datetime.datetime.strptime(need_time, '%Y-%m-%d %H:%M')
            # 将datetime对象转换为时间戳（Unix时间戳）
            new_timestamp = int(dt_obj.timestamp())
            now_timestamp = int(time.time())
            # 将时间戳转换为datetime对象
            dt1 = datetime.datetime.fromtimestamp(new_timestamp)
            dt2 = datetime.datetime.fromtimestamp(now_timestamp)
            # 计算差值
            delta = dt1 - dt2
            # 获取相差的天数、小时数、分钟数和秒数
            days = delta.days
            hours, remainder = divmod(delta.seconds, 3600)
            minutes, seconds = divmod(remainder, 60)

            show_string = f"相差 {days} 天 {hours} 小时 {minutes} 分钟 {seconds} 秒"
        except Exception as e:
            show_string = "输入有误"
    can_time_stamp_show_input.configure(text=show_string)  # 重新设置标签文本
    window.after(100, can_time_stamp_show)  # 每隔1s调用函数 get_now_time 自身获取时间


window = tkinter.Tk()

with open('tmp.ico', 'wb') as tmp:
    tmp.write(base64.b64decode(Icon().img))
window.iconbitmap('tmp.ico')
os.remove('tmp.ico')

width = window.winfo_screenwidth()
window.title('小工具 @author  >> henry.oulen@gmail.com')

# 获取屏幕尺寸计算参数，使窗口显示再屏幕中央
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
_width = 1920
_height = 1080
window_size = f'{_width}x{_height}+{round((screen_width - width) / 2)}+{round((screen_height - _height) / 2)}'  # round去掉小数

window.wm_state("zoomed")  # 设置打开的窗口最大化

# 周几
dat_num_label = tkinter.Label(window, text='', fg='#FFFFFF', font="等线 20 bold", bg="#5891E6")
dat_num_label.place(relx=0.3, rely=0.02, relwidth=0.05, relheight=0.05)
handle_week_nums()

# 当前时间
now_time_label = tkinter.Label(window, text='', fg='#FFFFFF', font="等线 20 bold", bg="#5891E6")
now_time_label.place(relx=0.35, rely=0.02, relwidth=0.2, relheight=0.05)
get_now_time()

# 自定义倒计时间
can_time_stamp_input = Entry(window, font="等线 16 bold", )
can_time_stamp_input.place(relx=0.6, rely=0.02, relwidth=0.15, relheight=0.05)
# 当前时间

can_time_stamp_show_input = tkinter.Label(window, text='', fg='#FFFFFF', font="等线 20 bold", bg="#5891E6")
can_time_stamp_show_input.place(relx=0.75, rely=0.02, relwidth=0.2, relheight=0.05)
can_time_stamp_show()

# 天气
weather_stamp_show = tkinter.Label(window, text='天气', font="等线 12 bold", fg="#FFFFFF", bg="#5891E6")
weather_stamp_show.place(relx=0.05, rely=0.01, relwidth=0.2, relheight=0.1)
get_current_weather()

time_stamp_show = Label(window, text='时间戳', font="等线 16 bold")
time_stamp_show.place(relx=0.05, rely=0.1, relwidth=0.1, relheight=0.07)
time_stamp_input = Entry(window, font="等线 16 bold", )
time_stamp_input.place(relx=0.05, rely=0.15, relwidth=0.1, relheight=0.05)

time_formate_show = Label(window, text='时间格式', font="等线 16 bold")
time_formate_show.place(relx=0.15, rely=0.1, relwidth=0.1, relheight=0.07, )
time_formate_input = Entry(window, font="等线 16 bold", justify="center", )
time_formate_input.place(relx=0.15, rely=0.15, relwidth=0.1, relheight=0.05)

timestamp_to_formate = tkinter.Button(window, text="时间戳-->格式化", command="handle_timestamp_formate",
                                      activebackground="#0f73ef",
                                      font="等线 16 bold")
timestamp_to_formate.bind("<Button-1>", handle_timestamp_formate)
timestamp_to_formate.place(relx=0.05, rely=0.2, relwidth=0.1, relheight=0.05)

formate_to_timestamp = tkinter.Button(window, text="时间格式-->时间戳", command="handle_formate_timestamp",
                                      activebackground="#0f73ef",
                                      font="等线 16 bold")
formate_to_timestamp.bind("<Button-1>", handle_formate_timestamp)
formate_to_timestamp.place(relx=0.15, rely=0.2, relwidth=0.1, relheight=0.05)

last_print_text = tkinter.Text(window, width=40, height=10, border=4, relief=RAISED, font="等线 16 bold", )
last_print_text.place(relx=0.05, rely=0.25, relwidth=0.2, relheight=0.1)

clp_text = tkinter.Button(window, text="复制到粘贴板",
                          command=copy_to_clipboard, activebackground="#0f73ef", font="等线 16 bold")
clp_text.place(relx=0.05, rely=0.35, relwidth=0.2, relheight=0.05)

# 定义消息对话框
last_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="节日倒数", command=local_day_laster,
                             font="等线 16 bold")
last_button.pack()
last_button.place(relx=0.05, rely=0.42, relwidth=0.05, relheight=0.05)

get_hot_news_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="今日热榜",
                                     command=local_get_hot_news,
                                     font="等线 16 bold")
get_hot_news_button.pack()
get_hot_news_button.place(relx=0.125, rely=0.42, relwidth=0.05, relheight=0.05)

get_today_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="历史今天", command=local_get_today,
                                  font="等线 16 bold")
get_today_button.pack()
get_today_button.place(relx=0.2, rely=0.42, relwidth=0.05, relheight=0.05)

last_print_text_answer = tkinter.Text(window, width=40, height=10, border=4, relief=RAISED, font="等线 13 bold", )
last_print_text_answer.place(relx=0.05, rely=0.50, relwidth=0.2, relheight=0.45)

# python日志使用
# 右边
sting_input = tkinter.Entry(window, font="等线 16 bold", )
sting_input.place(relx=0.3, rely=0.1, relwidth=0.28, relheight=0.05)

sting_input_button = tkinter.Button(window, text="Json格式化", activebackground="#0f73ef", font="等线 16 bold")
sting_input_button.bind("<Button-1>", handle_to_json)
sting_input_button.place(relx=0.55, rely=0.1, relwidth=0.1, relheight=0.05)

# baidu_btn_button = tkinter.Button(window, text="文心一言", command=start_request_baidu,
#                                   activebackground="#0f73ef",
#                                   font="等线 16 bold")
# baidu_btn_button.place(relx=0.65, rely=0.1, relwidth=0.1, relheight=0.05)

sting_clean_button = tkinter.Button(window, text="清空内容", command="handle_formate_timestamp",
                                    activebackground="#0f73ef",
                                    font="等线 16 bold")
sting_clean_button.bind("<Button-1>", clean_input)
sting_clean_button.place(relx=0.75, rely=0.1, relwidth=0.1, relheight=0.05)

clp_json = tkinter.Button(window, text="复制到粘贴板",
                          command=copy_to_json_clipboard, activebackground="#0f73ef", font="等线 16 bold")
clp_json.place(relx=0.85, rely=0.1, relwidth=0.1, relheight=0.05)

sting_output_button = tkinter.Text(window, width=40, height=10, border=4, relief=RAISED, font="等线 16 bold", )
sting_output_button.place(relx=0.3, rely=0.15, relwidth=0.65, relheight=0.8)

print(f"Successfully start run json tools {datetime.datetime.now()}")
window.mainloop()
